package com.ljl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * @author 刘家良
 * @date 2022/10/26 00:36
 * @description
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        String host = "127.0.0.1";
        int port = 7035;

        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup loopGroup = new NioEventLoopGroup(1);
        ChannelFuture sync = bootstrap.group(loopGroup)
                //保持连接
                .option(ChannelOption.SO_KEEPALIVE, true)
                .channel(NioSocketChannel.class)
                //客户端通道连接时，初始化方法
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringDecoder(Charset.forName("gbk")));
                        pipeline.addLast(new StringEncoder(Charset.forName("gbk")));
                        pipeline.addLast(new ClientMsgHandler());
                    }
                })
                .connect(host, port).sync();

        System.out.println("客户端成功连接！");
        //等待断开连接
        sync.channel().closeFuture().sync();

        //资源清理
        loopGroup.shutdownGracefully();
    }
}
